use std::env;
use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};
use std::thread;

#[tokio::main]
async fn main() {
    let args: Vec<String> = env::args().collect();
    let url = match args.get(1) {
        Some(arg) => arg,
        None => {
            eprintln!("Please provide a URL as a command-line argument");
            return;
        }
    };

    // 设置参数
    let num_threads = 10;  // 线程数量
    let num_requests = 100;  // 每个线程的请求数量

    // 创建共享计数器
    let counter = Arc::new(AtomicUsize::new(0));

    // 启动线程进行请求
    let mut handles = vec![];
    for _ in 0..num_threads {
        let url = url.clone();
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            tokio::runtime::Runtime::new().unwrap().block_on(async {
                for _ in 0..num_requests {
                    make_request(&url).await;
                    counter.fetch_add(1, Ordering::Relaxed);
                }
            });
        });
        handles.push(handle);
    }

    // 等待所有线程完成
    for handle in handles {
        handle.join().unwrap();
    }

    // 输出请求计数
    let total_requests = counter.load(Ordering::Relaxed);
    println!("Total requests: {}", total_requests);
}

async fn make_request(url: &str) {
    match reqwest::get(url).await {
        Ok(response) => {
            match response.text().await {
                Ok(body) => {
                    println!("body = {:?}", body);
                }
                Err(error) => {
                    eprintln!("Error reading response body: {}", error);
                }
            }
        }
        Err(error) => {
            eprintln!("Error making request: {}", error);
        }
    }
}
